<?php

class Response
{
	protected $_adapter;
	protected $_body;
	protected $_headers = array();
    protected $_header_group = array();
    protected $_code = 0;

	protected $_followLocation = array();
	protected $_version;
	public function __construct(Curl $curl)
	{
		$this->_adapter = $curl;
		$this->load($curl->exec());
	}
	public function getAdapter(){
		return $this->_adapter;
	}
	
	protected function load($re)
	{
		$lines = explode("\n", $re);

		if(preg_match("/HTTP\/(\d+\.\d+) (\d+)/is", $lines[0], $match)) {
            $this->_headers = array();
            $this->_version = $match[1];
			$this->_code = $match[2];
			unset($lines[0]);
            foreach($lines AS $k=>$v) {
                unset($lines[$k]);
                $line = trim($v);
                if(empty($line)) {
                    return $this->load(implode("\n", $lines));
                }
                $h = explode(':', $line);
                $this->_headers[$h[0]] = trim($h[1]);
            }
            $this->_header_group = $this->_headers;
        }
		$this->_body = implode("\n", $lines);
	}
	
	public function getBody()
	{
		return $this->_body;
	}
	


	public function setBody($body = null)
	{
		if ($body && is_string($body)) {
			$this->_body = $body;
		}
	}
	
	/**
	 * 服务器响应头部信息.
	 * @return multitype:
	 */
	public function getHeaders()
	{
		return $this->_headers;
	}
	
	/**
	 * 反回Location 过程headers.
	 * @return multitype:
	 */
	public function getFollowLocation()
	{
		return $this->_followLocation;
	}
	
	/**
	 * 得到头部信息值 .
	 * @param unknown_type $k
	 * @return multitype:
	 */
	public function getHeader($k)
	{
		if(isset($this->_headers)) {
			return $this->_headers[$k];
		}
	}
	
	public function getEncoding()
	{
		return $this->getHeader('Content-Encoding');
 	}

    public function getCharset()
    {
        if($h = $this->getHeader('Content-Type')) {
            if(preg_match('/charset=([\w\-\d]+)/i', $h, $match)) {
                return $match[1];
            } elseif(preg_match("/charset=([\w\-\d]+)/Usi", $this->getBody(), $match)) {
                return $match[1];
            }
        }
    }


    public function getStatus()
	{
		return $this->_code;
	}
	
	public function refresh()
	{
		$this->load($this->_adapter->exec());
		return $this;
	}
	
	public function getVersion()
	{
		return $this->_version;
	}
	public function __toString()
	{
		return strval($this->getBody());
	}
	
	public function __destruct()
	{
		//echo 'response finsh..';
	}
	
}
class Curl 
{
	protected $_options = array();
	protected $_ch;
	protected $_headers = array();

    protected $_proxy;

	public function __construct()
	{
		$this->init();
		$this->setUserAgent('Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36');
		$this->setFollowLocation(2);
		$this->setAutoReferer(1);
	}
	
	public function init()
	{
		$this->_ch = curl_init();
		$this->setOpt(CURLOPT_HEADER, 1);
		$this->setOpt(CURLOPT_SSL_VERIFYPEER, 0);//对认证证书来源的检查
		$this->setOpt(CURLOPT_SSL_VERIFYHOST, 2);//从证书中检查SSL加密算法是否存
		$this->setAcceptEncoding('gzip');
	}
	
	/**
	 * 开启cookie功能.
	 * @param unknown_type $file
	 * @return 
	 */
	
	/*public function enableCookie($file = null)
	{
		if($file === null) {
			$cookie = new system_var_tmp();
			$file = $cookie->getFile();
		}
		$this->setOpt(CURLOPT_COOKIEJAR, $file);
		$this->setopt(CURLOPT_COOKIEFILE, $file);
		return $this;
	}
	*/

	/**
	 * 
	 * @param unknown_type $version CURLOPT_VERSION_!_0
	 * @return cooper_http_adapter_curl
	 */
	public function setVersion($version)
	{
		$this->setOpt(CURLOPT_HTTP_VERSION, $version);
		return $this;
	}
	
	public function getHandle()
	{
		return $this->_ch;
	}
	
	public function setHeader($k, $val)
	{
		$this->_headers[$k] = $val;
		return $this;
	}
	
	public function getHeader($k)
	{
		if(isset($this->_headers[$k])) {
			return $this->_headers;
		}
	}
	
	public function setHeaders($list)
	{
		$this->_headers = $list;
		return $this;
	}

    public function getHeaders()
    {
        return $this->_headers;
    }
	
	/**
	 * 是否自动处理跳转地址到最终地址.
	 * @param unknown_type $val
	 * @return cooper_http_adapter_curl
	 */
	public function setFollowLocation($val)
	{
		$this->setOpt(CURLOPT_FOLLOWLOCATION, intval($val));
		return $this;
	}
	
	/**
	 * 设置自动referer信息.
	 * @param unknown_type $val
	 * @return cooper_http_adapter_curl
	 */
	public function setAutoReferer($val)
	{
		$this->setOpt(CURLOPT_AUTOREFERER, $val);
		return $this;
	}
	
	public function setAcceptEncoding($encoding = 'gzip')
	{
		$this->setOpt(CURLOPT_ENCODING, $encoding);
		$this->setHeader('Accept-Encoding', $encoding);	
		return $this;
	}
	
	public function getEncoding()
	{
		return $this->getHeader('Accept-Encoding');
	}
	
	public function setAcceptLanguage($lang)
	{
		$this->setHeader('Accept-Language', $lang);
		return $this;
	}
	
	public function setUserAgent($val)
	{
		$this->setOpt(CURLOPT_USERAGENT, $val);
		return $this;
	}
	
	
	
	/**
	 * 设置请求超时秒数.
	 * @param unknown_type $time
	 * @return cooper_http_adapter_curl
	 */
	public function setTimeout($time = 10)
	{
		$this->setOpt(CURLOPT_TIMEOUT, $time);
		return $this;
	}
	
	
	
	/**
	 * 
	 * @param unknown_type $opt
	 * @param unknown_type $val
	 */
	public function setOpt($opt, $val)
	{
		curl_setopt($this->getHandle(), $opt, $val);		
		return $this;
	}
	
	/**
	 * GET 请求.
	 * @param unknown_type $url
	 * @param unknown_type $query
	 * @return Ambigous <cooper_http_respone, cooper_http_response>
	 */
	public function get($url, $query = array())
	{
        if($this->_proxy) {
            $this->autoProxy();
        }
		if($query) {
			$url.='?'.http_build_query($query);
		}
		$this->setOpt(CURLOPT_HTTPGET, 1);
		return $this->request($url);
	}
	
	/**
	 * POST 请求.
	 * @param unknown_type $url
	 * @param unknown_type $query
	 * @return Ambigous <cooper_http_respone, cooper_http_response>
	 */
	public function post($url, $query = null)
	{
		if(is_array($query)) {
			$query = http_build_query($query);
		}
		$this->setOpt(CURLOPT_POSTFIELDS, $query);
		$this->setOpt(CURLOPT_POST, 1);
		$this->setOpt(CURLOPT_REFERER,$url); //伪造来路
		return $this->request($url);
	}

	/**
	 * 执行并反回执行结果.
	 * @return mixed
	 */
	public function exec()
	{
		$this->setOpt(CURLOPT_RETURNTRANSFER, 1);
		return curl_exec($this->getHandle());
		//$ch = curl_copy_handle($this->getHandle());
		//$re = curl_exec($ch);
		//curl_close($ch);
		//return $re;
	}
	
	public function __destruct()
	{
		curl_close($this->_ch);
	}
	
	static protected $_instance;
	/**
	 * 单一化实例方法.
	 * @return cooper_http_adapter_curl
	 */
	static public function getInstance()
	{
		return new self();
	}
	public function get_html_box($s,$e,$page){
		$ex =  explode($s,$page);
		if(isset($ex[1])){
			$ex1 =  explode($e,$ex[1]);
			return $ex1[0];
		}else{
			return "";
		}
	}
	/**
	 * 
	 * @return cooper_http_respone
	 */
	public function request($url)
	{
		$url = trim($url);
		if($this->_headers) {
            $headers = array();
            foreach($this->_headers AS $k=>$v) {
				$headers[] = $k.': '.$v;
			}
			$this->setOpt(CURLOPT_HTTPHEADER, $headers);
		}
		$this->setOpt(CURLOPT_URL, $url);
		return new Response($this);
	}
  
}
